package com.xutong.myfunction.Utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.widget.ImageView;

import java.util.HashMap;

/**
 * Created by hasee on 2016/9/26.
 */
public class ImageDownloadUtils{

    private static Context mContext;

    private static ImageView imageView;

    private static int defImageId = 0;

    private static int loadImageId = 0;

    private static HashMap<String,ImageView> hashMap = new HashMap<>();


    public static void init(Context context){
        mContext = context;
    }

    /**
     * 加载图片并显示
     * @param url 图片url
     * @param iv ImageView控件
     * @param loadingImageId 加载中显示的图片id
     * @param errImageId 加载失败显示的图片id
     */
    public static void disPlayImage(String url,ImageView iv,int loadingImageId,int errImageId){
        imageView = iv;
        hashMap.put(url,imageView);
        loadImageId = loadingImageId;
        defImageId = errImageId;
        new ImageDownloadTask().execute(url,String.valueOf(defImageId));
    }

    /**
     * 加载图片并显示
     * @param url 图片的url
     * @param iv ImageView控件
     * @param errImageId 加载失败显示的图片id
     */
    public static void disPlayImage(String url,ImageView iv,int errImageId){
        imageView = iv;
        hashMap.put(url,imageView);
        defImageId = errImageId;
        new ImageDownloadTask().execute(url,String.valueOf(defImageId));
    }


    private static class ImageDownloadTask extends AsyncTask<String,ImageView,Bitmap> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected Bitmap doInBackground(String... params) {
            ImageView iv = hashMap.get(params[0]);
            publishProgress(iv);
            Bitmap bitmap = HttpUtils.getDownload(mContext,params[0],params[1]);
            if (bitmap!=null){
                hashMap.put(bitmap.toString(),iv);
                return bitmap;
            }else {
                hashMap.put("null",iv);
                return null;
            }


        }

        @Override
        protected void onProgressUpdate(ImageView... values) {
            super.onProgressUpdate(values);
            if (loadImageId != 0) {
                values[0].setImageResource(loadImageId);
            }

        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {
            super.onPostExecute(bitmap);
            if (bitmap != null) {
                ImageView iv = hashMap.get(bitmap.toString());
                iv.setImageBitmap(bitmap);
            } else {
                if (defImageId != 0) {
                    ImageView iv = hashMap.get("null");
                    iv.setImageResource(defImageId);
                }

            }

        }
    }

}
